#pragma once
#include <string>
#include <vector>
#include <algorithm>
#include "TextFingerPrintIterator.h"
#include <db_cxx.h>

int compareIntKeys(Db *dbp, const Dbt *pKeya, const Dbt *pKeyb);
int compareIntValues(Db *dbp, const Dbt *pValuea, const Dbt *pValueb);

class TextFPLocationBDB
{
public:
	TextFPLocationBDB(std::string &path, std::string &name, bool isWrite = false);
    ~TextFPLocationBDB(void) { close(); };
    void    setParameters(HashValue_t radix, HashValue_t q, int winLength, std::string &txtFileName, FILE *tFile);
    void    setPattern(const char* pPat);
	int     putBDBRec(HashValue_t pKey, FilePosition_t pValue);
	int     getLocsForFP(HashValue_t pKey, std::vector<FilePosition_t> &pLocationVector);
	int     getLocsForFPRange(HashValue_t fromKey, HashValue_t toKey, std::vector<FilePosition_t> &pLocationVector);
	int     getLocsForPartialFP(HashValue_t pStartFP, std::vector<FilePosition_t> &pLocationVector);
	void    showLocsInVector(std::vector<FilePosition_t> &pLocationVector);
	void    sortLocsInVector(std::vector<FilePosition_t> &pLocationVector);
    int     getLocsForPattern(std::vector<FilePosition_t> &pLocationVector);
    int     getMatchesInTextFile(std::vector<FilePosition_t> &pLocationVector);
    void    writeResultsToFile(FILE * outFile, int pNumMatches, int pSpuriousHits);
    Db*     getDBHandle() {return &dbh_;};
    std::string getDBPath() {return dbPath_;};
private:
	Db          dbh_;
	Dbc        *pdbc_;
    std::string dbPath_;
    std::string dbName_;
    std::string dbExtension_;
	std::string dbFileName_;
	u_int32_t   cFlags_;
	bool        isWrite_;
    Dbt         dbKey_;
    Dbt         dbValue_;

    // these member variables are the parameters used to calculate fingerprints
    // and build the BerkeleyDB index database
    HashValue_t radix_;
    HashValue_t modulo_;
    int         winLength_;
    std::string txtFileName_;
    FILE*       txtFile_;

    // these member variables contain the details about a search pattern
    std::string                 searchPattern_;
    int                         sPatternLength_;
    std::vector<HashValue_t>    sPatternFPs_;
    int                         numKeysInPattern_;
    int                         lenOfShortPattern_;

	// Make sure the default constructor is private
	// We don't want it used.
	// 
	TextFPLocationBDB() : dbh_(NULL, 0) {}

	void close();
};